﻿using NaturalNote.Core.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NaturalNote.Mysql
{
    public class MysqlTrait : DbTrait
    {        

        public override IDbConnection GetConnection(string connectionString)
        {
            return new MySqlConnector.MySqlConnection(connectionString);
        }

        public override string InsertOnUpdateSql(TableInfo tableInfo)
        {            
            var columns = new List<string>();
            var propNames = new List<string>();
            var updateValues = new List<string>();
            foreach (var column in tableInfo.Columns)
            {
                columns.Add($"`{column.Name}`");
                propNames.Add($"@{column.PropName}");
                if (!column.IsPrimary)
                {
                    updateValues.Add($"`{column.Name}`=VALUES(`{column.Name}`)");
                }
            }
            var sql = @$"INSERT INTO `{tableInfo.Name}` (
{string.Join(",", columns)} ) 
VALUES ( {string.Join(",", propNames)} )
ON DUPLICATE KEY UPDATE {string.Join(",", updateValues)}";
            return sql;
        }

        public override string InsertSql(TableInfo tableInfo)
        {
            var columns = new List<string>();
            var propNames = new List<string>();
            
            foreach (var column in tableInfo.Columns)
            {
                columns.Add($"`{column.Name}`");
                propNames.Add($"@{column.PropName}");              
            }
            var sql = @$"INSERT INTO `{tableInfo.Name}` (
{string.Join(",", columns)} ) 
VALUES ( {string.Join(",", propNames)} ) ";
            return sql;
        }

        public override string QuoteSymbol(string str)
        {
            return $"`{str}`";
        }
    }
}
